package com.njitweb.service.impl;

import com.njitweb.enu.FileCategory;
import com.njitweb.service.FileService;
import com.njitweb.util.MD5Util;
import com.njitweb.util.MinioTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private MinioTemplate minioTemplate;

    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secretKey}")
    private String secretKey;
    @Value("${minio.endpoint}")
    private String endPoint;
    @Value("${minio.bucketName}")
    private String bucketName;

    @Override
    public Map<String, Object> upload(MultipartFile file) {
        String md5Name = MD5Util.getFileMD5(file);   //拿到文件的md5值

        String fileName = file.getOriginalFilename();

        String fileSuffix = fileName.substring(fileName.lastIndexOf("."));

        String folderName = generateFolderName(fileSuffix); //文件夹名称

        String objectName = folderName + md5Name + fileSuffix;  //objectName

        String fileUrl = endPoint + "/" + bucketName + "/" + objectName; //完整的URL

        minioTemplate.pubObject(objectName, file);  //存入到minio中去

        HashMap<String, Object> map = new HashMap<>();
        //存储map中返回给前端
        map.put("fileUrl", fileUrl);
        return map;
    }

    private String generateFolderName(String fileSuffix) {
        String fileBucket = getFileBucket(fileSuffix);
        if (fileBucket == null) {
            return null;
        }
        // 获取当前日期
        Date now = new Date();
        // 使用 SimpleDateFormat 来格式化日期为 "yyyy/MM/dd" 格式
        DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String date = sdf.format(now);
        // 组合最终的文件夹路径：如 "image/2024/11/30/"
        return fileBucket + date + "/";
    }

    private static String getFileBucket(String fileSuffix) {
        return FileCategory.getBucketPrefixByExtension(fileSuffix);
    }
}
